package com.heroCW.bodhiAttic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heroCW.bodhiAttic.common.BaseContext;
import com.heroCW.bodhiAttic.entity.AddressBook;
import com.heroCW.bodhiAttic.mapper.AddressBookMapper;
import com.heroCW.bodhiAttic.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Slf4j
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {


    @Override
    public Boolean saveAddressBook(AddressBook addressBook) {

        LambdaQueryWrapper<AddressBook> addressBookWrapper = new LambdaQueryWrapper<>();
        addressBookWrapper.eq(AddressBook::getUserId, addressBook.getUserId());
        int addressBookCount = count(addressBookWrapper);

        // 如果是第一个收货地址，则自动修改为默认状态
        if (addressBookCount == 0) {
            addressBook.setIsDefault(1);
        }

        return save(addressBook);
    }

    @Override
    public List<AddressBook> getList(AddressBook addressBook) {
        //条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);

        //SQL:select * from address_book where user_id = ? order by update_time desc
        return this.list(queryWrapper);
    }

    @Override
    public AddressBook getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);

        //SQL:select * from address_book where user_id = ? and is_default = 1
        return this.getOne(queryWrapper);
    }

    @Override
    @Transactional
    public Boolean setDefault(AddressBook addressBook) {
        Boolean[] flags = new Boolean[2];
        LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        wrapper.set(AddressBook::getIsDefault, 0);
        //SQL:update address_book set is_default = 0 where user_id = ? and is_default = 1
        flags[0]=this.update(wrapper);

        addressBook.setIsDefault(1);
        //SQL:update address_book set is_default = 1 where id = ?
        flags[1]=this.updateById(addressBook);

        for (Boolean flag : flags) {
            if (!flag)
                return false;
        }
        return true;
    }
}
